export default{
    namespaced:true,
    state: ()=>({
      cart: JSON.parse(uni.getStorageSync('cart') || '[]')
    }),
    mutations:{
      addToCarts(state,goods){
        let findResult = state.cart.find(item=>item.goods_id === goods.goods_id)
        if(!findResult){
          state.cart.push(goods)
        }else{
          findResult.goods_count++
        }
        this.commit('m_cart/saveShopCart')
      },
      saveShopCart(state){
        uni.setStorageSync('cart',JSON.stringify(state.cart))
      },
      updateGoodsState(state,goods){
        let findResult = state.cart.find(item=>item.goods_id === goods.goods_id)
        if(findResult){
        
          findResult.goods_state= goods.goods_state
        }
        this.commit('m_cart/saveShopCart')
      },
      updateGoodsCount(state,goods){
        
        console.log('vuex' + goods);
        const findResult = state.cart.find(item=>item.goods_id === goods.goods_id)
        if(findResult){
        
          findResult.goods_count = goods.goods_count
          
          this.commit('m_cart/saveShopCart')
         
        }
       
      },
      removeGoodsById(state,goods_id){
        state.cart = state.cart.filter(item=>item.goods_id !== goods_id)
        this.commit('m_cart/saveShopCart')
      },
      updateAllGoodsState(state,newState){
        state.cart.forEach(item => item.goods_state = newState)
        this.commit('m_cart/saveShopCart')
      },
      
    },
    getters:{
      total(state){
   
        return state.cart.reduce((sum,next)=>{
          return  sum + next.goods_count
        },0)
      },
      checkedCount(state){
        return state.cart.filter(item=>item.goods_state)
        .reduce((total,item)=>total += item.goods_count,0)
      },
      checkedGoodsAmount(state){
        return state.cart.filter(item => item.goods_state).reduce((total,item)=>total + item.goods_count*item.goods_price,0).toFixed(2)
      }
    },
    
}